﻿using System;
using System.Text.RegularExpressions;
using RuTracker.Interface;

namespace RuTrackerLib.Editors.Links
{
    public class Link : ICloneable<Link> 
    {
        private const string HrefSearchPattern = "href\\s*=\\s*\"(?<href>.*?)\"";
        private const string TypeSearchPattern = "type\\s*=\\s*\"(?<type>.*?)\"";
        private string _href;
        private string _type;

        public Link(string html)
        {
            Html = html;
            _href = ParseHref();
            _type = ParseType();

            if (string.IsNullOrEmpty(HRef))
                throw new ArgumentException("href attribute cannon be found");
        }

        public string Html { get; private set; }
        public string HRef
        {
            get { return _href; }
            set
            {
                _href = value;
                SetHref(value);
            }
        }

        public string Type
        {
            get { return _type; } 
            set
            {
                _type = value;
                SetType(value);
            }
        }

        private void SetHref(string href)
        {
            Regex regex = new Regex(HrefSearchPattern);
            Html = Html.Replace(regex.Match(Html).Groups["href"].Value, href);
        }

        private string ParseHref()
        {
            Regex regex = new Regex(HrefSearchPattern);
            Match match = regex.Match(Html);
            return match.Groups["href"].Success ? match.Groups["href"].Value : string.Empty;
        }

        private string ParseType()
        {
            Regex regex = new Regex(TypeSearchPattern);
            Match match = regex.Match(Html);
            return match.Groups["type"].Success ? match.Groups["type"].Value : string.Empty;
        }

        private void SetType(string type)
        {
            Regex regex = new Regex(TypeSearchPattern);
            if (regex.Match(Html).Groups["type"].Success)
            {
                Html = Html.Replace(regex.Match(Html).Groups["type"].Value, type);
            }
            else
            {
                Html = Html.Insert(2, string.Format(" type=\"{0}\"", type));
            }
        }

        public Link Clone()
        {
            return new Link(Html);
        }

        public override string ToString()
        {
            return Html;
        }

        object ICloneable.Clone()
        {
            ICloneable<Link> thisClass = this;
            return thisClass.Clone();
        }
    }
}
